package com.cloudkinto.service.shop.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.DicBusinessItemDao;
import com.cloudkinto.dao.ShopDao;
import com.cloudkinto.dao.UserDao;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.DicBusinessItemDo;
import com.cloudkinto.entity.ShopDo;
import com.cloudkinto.entity.UserDo;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.shop.vo.ShopAddReq;
import com.cloudkinto.service.shop.vo.ShopPageRes;
import com.cloudkinto.service.shop.vo.ShopUpdateReq;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-01
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class ShopServiceImpl extends ServiceImpl<ShopDao, ShopDo> implements ShopService {
    @Autowired
    private ShopDao dao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyService companyService;

    @Override
    public SingleResult addInit() {
        List<Map> result = new ArrayList<>();

        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.platform);
        List<DicBusinessItemDo> itemDoList = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(itemDoList)) {
            for (DicBusinessItemDo itemDo : itemDoList) {
                Map map = new HashMap();
                map.put("id", itemDo.getId());
                map.put("value", itemDo.getDicItemValue());
                result.add(map);
            }
        }
        return SingleResult.success(result);
    }

    @Override
    public ShopAddReq add(ShopAddReq req, Long userId, Long companyId) {
        addCheck(req, companyId);
        ShopDo entityDo = new ShopDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        entityDo.setCompanyId(companyId);
        dao.insert(entityDo);
        return req;
    }

    @Override
    public ShopDo add(ShopDo req) {
        ShopDo entityDo = new ShopDo();
        QueryWrapper<ShopDo> shopDoWrapper = new QueryWrapper<>();
        shopDoWrapper.eq("shop_name", req.getShopName());
        shopDoWrapper.eq("company_id", req.getCompanyId());
        shopDoWrapper.last("limit 1");
        Integer count = dao.selectCount(shopDoWrapper);
        if (count > 0)
            entityDo = dao.selectOne(shopDoWrapper);
        handlerAddBefore(entityDo, null);
        if (entityDo.getId() == null) {
            dao.insert(req);
        } else {
            entityDo.setShopName(req.getShopName());
            entityDo.setShopifyHost(req.getShopifyHost());
            entityDo.setShopifyToken(req.getShopifyToken());
            entityDo.setShopifyKey(req.getShopifyKey());
            entityDo.setShopifySecret(req.getShopifySecret());
            entityDo.setUpdateTime(new Date());
            dao.updateById(entityDo);
        }
        return req;
    }

    //新增校验
    private void addCheck(ShopAddReq req, Long companyId) {
        LambdaQueryWrapper<ShopDo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(ShopDo::getShopName, req.getShopName()).eq(ShopDo::getCompanyId, companyId);
        int count = this.baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BizExceptionI18(SysConstant.Shop_Check_Name);
        }
    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(ShopDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(ShopDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success(detail(id));
    }

    @Override
    public Object update(ShopUpdateReq req, Long userId) {
        ShopDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return entityDo;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(ShopDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(ShopDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        ShopDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        dao.updateById(entityDo);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(ShopDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public ShopUpdateReq detail(Long id) {
        ShopDo entityDo = dao.selectById(id);
        ShopUpdateReq res = new ShopUpdateReq();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private ShopUpdateReq handlerDetailAfter(ShopUpdateReq res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<ShopPageRes> getList(Map<String, String> map) {
        QueryWrapper<ShopDo> wrapper = queryBuild(map);
        List<ShopDo> list = this.list(wrapper);
        List<ShopPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<ShopDo> wrapper = queryBuild(map);
        IPage<ShopDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<ShopPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<ShopPageRes> handlerListAfter(List<ShopDo> list) {
        List<ShopPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (ShopDo shopDo : list) {
                ShopPageRes res = new ShopPageRes();
                BeanUtils.copyProperties(shopDo, res);
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(shopDo.getPlatformId());
                if (businessItemDo != null) {
                    res.setPlatform(businessItemDo.getDicItemValue());
                }
                result.add(res);
            }
        }
        return result;
    }

    private IPage<ShopDo> pageInit(Map<String, String> map) {
        IPage<ShopDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<ShopDo> queryBuild(Map<String, String> map) {
        QueryWrapper<ShopDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("shopName"))) {
            wrapper.like("shop_name", map.get("shopName"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        wrapper.orderByDesc("id");
        return wrapper;
    }

    @Override
    public ShopDo getShopTokenById(long shopId) {
        return baseMapper.selectById(shopId);
    }

    @Override
    public List<Map> selectShopListInit(Long userId, Long companyId) {
        List<Map> shopList = new ArrayList<>();
        List<ShopDo> shopDoList;
        if (companyId == 1) {
            shopDoList = dao.selectList(new LambdaQueryWrapper<ShopDo>().eq(ShopDo::getCompanyId, companyId));
        } else {
            UserDo userDo = userDao.selectById(userId);
            QueryWrapper<ShopDo> shopWrapper = new QueryWrapper<>();
            if (userDo != null && userDo.getShopId() != null)
                shopWrapper.eq("id", userDo.getShopId());
            shopWrapper.eq("company_id", companyId);
            shopDoList = dao.selectList(shopWrapper);

        }
        for (ShopDo shopDo : shopDoList) {
            Map shopMap = new HashMap();
            shopMap.put("id", shopDo.getId());
            shopMap.put("value", shopDo.getShopName());
            shopList.add(shopMap);
        }
        return shopList;
    }

    @Override
    public List<Map> selectShopListInitByUserId(Long userId) {
        List<Map> shopList = new ArrayList<>();
        List<ShopDo> shopDoList;
        UserDo userDo = userDao.selectById(userId);
        QueryWrapper<ShopDo> shopWrapper = new QueryWrapper<>();
        if (userDo != null && userDo.getShopId() != null)
            shopWrapper.eq("id", userDo.getShopId());
        shopWrapper.eq("company_id", userDo.getCompanyId());
        shopDoList = dao.selectList(shopWrapper);
        if (!CollectionUtils.isEmpty(shopDoList)) {
            for (ShopDo shopDo : shopDoList) {
                Map shopMap = new HashMap();
                shopMap.put("id", shopDo.getId());
                shopMap.put("value", shopDo.getShopName());
                shopList.add(shopMap);
            }
        }
        return shopList;
    }

    @Override
    public boolean setAutoStock(Long companyId, int setFlag) {
        CompanyDo companyDo = companyService.getById(companyId);
        if (companyDo.getAutoStock()==setFlag) {
            return false;
        }else {
            companyDo.setAutoStock(setFlag);
            companyDo.setUpdateTime(new Date());
            companyService.updateById(companyDo);
        }
        return false;
    }

    @Override
    public int getAutoStock(Long companyId) {
        CompanyDo companyDo = companyService.getById(companyId);
        return companyDo.getAutoStock();
    }

    @Override
    public List<Map<String, Object>> getShopList(Long companyId) {
        List<Map<String, Object>> shopList = new ArrayList<>();
        QueryWrapper<ShopDo> shopWrapper = new QueryWrapper<>();
        if (companyId!=null)
        shopWrapper.eq("company_id",companyId);
        List<ShopDo> shopDoList = dao.selectList(shopWrapper);
        if (!CollectionUtils.isEmpty(shopDoList)) {
            for (ShopDo shopDo : shopDoList) {
                Map<String, Object> shopMap = new HashMap<>();
                shopMap.put("id", shopDo.getId());
                shopMap.put("value", shopDo.getShopName());
                shopMap.put("companyId", shopDo.getCompanyId());
                shopList.add(shopMap);
            }
        }
        return shopList;
    }

    @Override
    public Map<Long, String> getShopListMap(Long companyId) {
        QueryWrapper<ShopDo> shopWrapper = new QueryWrapper<>();
        if (companyId!=null)
            shopWrapper.eq("company_id",companyId);
        List<ShopDo> shopDoList = dao.selectList(shopWrapper);
        Map<Long, String> collect = shopDoList.stream().collect(Collectors.toMap(ShopDo::getId, ShopDo::getShopName));
        return collect;
    }
}
